<template>
	<div class="chatPageBox">
		<view class="chatPage">
			<view class="chatContainer">
				<view class="chatContent">
					<scroll-view :scroll-top="scrollTop" :scroll-with-animation="true" class="scroll" scroll-y="true">
						<template v-for="(message, index) in chatList" class="QueryMessages-list">
							<div v-if="message.timeTag" class="timeTag">
								<span>{{ message.timeTag }}</span>
							</div>
							<div v-if="messageBelong(message) === 'system'" class="message system">
								<Message :belong="`system`" :message="message"></Message>
							</div>
							<div v-else-if="messageBelong(message) === 'user'" class="message user">
								<div class="msg">
									<!-- 								<template v-if="false">
										<span v-if="groupMessage.users[uid]" class="name">{{ groupMessage.users[uid].showUserName }}</span>
									</template> -->
									<div class="msg_core">
										<span v-if="message.sentStatus == 3" class="info_icon sendStatus-3"
											@click="handleResend(message)"></span>
										<div v-if="message.sentStatus == 1" class="sentStatus-1">
											<div>发送中...</div>
										</div>
										<Message :belong="`user`" :message="message" @openImage="openImage"
											@openRichLink="openRichLink"></Message>
									</div>
								</div>

								<!-- <img v-if="groupMessage.users[uid]" :src="groupMessage.users[uid].showAvatar" alt="" class="avatar" /> -->
							</div>
							<div v-else-if="messageBelong(message) === 'to'" class="message to">
								<!-- <image :src="renderTargetAvatar(message.owner.userId)" alt="" class="avatar" /> -->
								<div class="msg">
									<!-- <span class="name">{{ message.owner.userName }}</span> -->
									<div class="msg_core">
										<Message :belong="`to`" :message="message" @openImage="openImage"
											@openRichLink="openRichLink"></Message>
									</div>
								</div>
							</div>
						</template>
					</scroll-view>
				</view>
				<view v-if="renderInput()" class="chatInput">
					<template>
						<inputText ref="input" @scrollBottom="scrollBottom" @sendImageMessage="sendImageMessage"
							@sendInputMessage="sendInputMessage"></inputText>
					</template>
				</view>
				<template v-if="startAnswer">
					<Diagnosis ref="answer" :hideQuestion="false" @submit="answerEvent"></Diagnosis>
				</template>
			</view>
		</view>
	</div>
</template>

<script>
	import zim, {
		zimApi,
		initGuideDiagnosis,
		tools
	} from './libs/drugSaasTr';
	import Message from './components/MessageComponent/index';
	import Diagnosis from './components/Diagnosis/index.vue';
	import inputText from './components/input/index.vue';

	// const avatarNull = `https://static.91jkys.com/attachment/20211009165743755_7d589835f3ff42759f7f7b5305f8bdbf.png`;
  const avatarNull = `https://static.foryor-in.com/attachment/20211009165743755_7d589835f3ff42759f7f7b5305f8bdbf.png`;
	let GuideDiagnosis = null;
	export default {
		components: {
			Message,
			Diagnosis,
			inputText,
		},
		data() {
			return {
				uid: '',
				advisoryId: '',
				chatList: [],
				UserCanSpeak: true,
				groupMessage: {
					groupUsers: [],
					users: {},
				},
				startAnswer: false,
				scrollTop: 0,
				advisoryIdKey: '', // 测试数据
				apigw: 'TRQA',   // ONLINE 线上   TRQA 测试
				biz: '' // GYJ新增代码
			};
		},
		onLoad(q) {
			if (q.advisoryIdKey) {
				// 服务端下发
				this.advisoryIdKey = q.advisoryIdKey;
			}
			if (q.applyId) {
				// 排查问题使用 缺少无法正常找到当前会话
				this.uid = q.applyId;
			}
			if (q.apigw) {
				//线上
				this.apigw = q.apigw;
			}
			// GYJ新增代码
			if (q.biz) {
				this.biz = q.biz
			}
			// ----------
			uni.setNavigationBarTitle({
				title: '问诊',
			});
			console.log(q, 'q');
			zim.setEnv({
				uid: this.uid,
				runtime: {
					env: 'MINIAPP',  // H5  MINIAPP
					apigw: this.apigw,
				},
				debug: false,
				db: false,
			});
			this.zyPreInit();
		},
		methods: {
			async zyPreInit() {
				this.eventInit();
				try {
					zim.destory() // GYJ新增代码
					const msg = await zim.Login(this.advisoryIdKey);
					this.uid = msg.submitterUcId;
					this.advisoryId = msg.advisoryId;
					zim.getInstance();
				} catch (e) {
					console.log('登陆失败', e);
				}
			},
			scrollBottom(t = 50) {
				setTimeout(() => {
					this.scrollTop = 99999999999999 + Math.random();
				}, t);
			},
			eventInit() {
				// 长连接相关事件
				zim.Listener.subscribe('onConnect', (e, msg) => {
					console.log('onConnect', e, msg);

					this.GuideDiagnosisEventInit();
				});
				zim.Listener.subscribe('onSendSuccess', (e, message) => {
					console.log('消息发送成功', message);
					this.chatList = this.chatList.map(el => {
						if (el.clientMsgId == message.clientMsgId) {
							return {
								...message,
								sentStatus: 2,
							};
						}
						return el;
					});
				});
				zim.Listener.subscribe('onMessage', (e, msg) => {
					console.log('收到消息', msg);
					if (msg.group.groupId == this.gid) {
						this.chatList.push(msg);
						this.scrollBottom();
					}
					// GYJ新增代码
					if (this.biz == 'RX') {
						if (msg.messageInfo.body.text.indexOf('正在为您开具处方') >= 0 && msg.owner.sysRole == "MANAGER") {
							// this.navigateBack()
							this.navigateToMiniProgram()
						}
					}
					// --------------
				});
				zim.Listener.subscribe('onSendFail', (e, msg) => {
					console.log('消息发送失败', msg);
					this.chatList = this.chatList.map(el => {
						if (el.clientMsgId == msg.message.clientMsgId) {
							return {
								...msg.message,
								sentStatus: 3,
							};
						}
						return el;
					});
				});
				zim.Listener.subscribe('onReconnectMaxTimes', (e, msg) => {
					console.log('超过最大重连次数');
				});
				zim.Listener.subscribe('onLoginout', (e, msg) => {
					console.log('onLoginout');
				});
				zim.Listener.subscribe('onClose', (e, msg) => {
					console.log('连接关闭 e', e);
          console.log('连接关闭 msg', msg);
				});
				zim.Listener.subscribe('onCustomBusiness', (e, msg) => {
					console.log('收到自定义消息', msg);
				});
				zim.Listener.subscribe('onUserSpeakStatusChange', (e, data) => {
					console.log('聊天状态已改变');
					const {
						groupid,
						status,
						userid
					} = data;
					if (this.uid == userid && groupid == this.gid) {
						if (status === 'CANSPEAK') {
							this.UserCanSpeak = true;
						} else {
							this.UserCanSpeak = false;
						}
					}
				});
				zim.Listener.subscribe('onReceiveServerMsg', (e, msg) => {
					if (msg.data.groupId == this.gid) {
						if (msg.errorCode == 'SHARE_IM-CAN_NOT_SPEAK') {
							console.log(msg.errorMessage);
							uni.showToast({
								title: msg.errorMessage,
								icon: 'none',
								duration: 2000
							});
						}
					}
				});
			},
			GuideDiagnosisEventInit() {
				this.UserCanSpeak = false;
				GuideDiagnosis = initGuideDiagnosis({
					advisoryId: this.advisoryId,
				});
				// 切换聊天房间事件订阅
				GuideDiagnosis.Listener.subscribe('drugstore.changeGroup', (e, data) => {
					this.gid = data.groupId;
					console.log('订阅切换组事件', data);
					this.getGroupInfo();
					this.getHistoryMsg();
				});
				GuideDiagnosis.Listener.subscribe('drugstore.question', (e, answer) => {
					console.log('订阅业务问题', answer);
					this.startAnswer = true;
					this.$nextTick(() => {
						this.$refs['answer'].start(answer);
						this.scrollBottom();
					});
				});
				GuideDiagnosis.Listener.subscribe('drugstore.endQuestion', (e, data) => {
					console.log('订阅结束导诊消息：', data);
					const {
						type,
						text
					} = data;
					this.startAnswer = false;
					this.robotShow = false;
					if (type === 'advisoryFinish') {
						this.UserCanSpeak = true;
					} else if (type === 'apiError') {
						this.UserCanSpeak = true;
						uni.showToast({
							title: text,
							duration: 2000,
							icon: 'error',
						});
						this.inputShow = false;
					} else {
						this.UserCanSpeak = true;
						uni.showToast({
							title: text,
							duration: 2000,
							icon: 'error',
						});
					}
					this.$emit('endQuestion', data);
				});
				GuideDiagnosis.Listener.subscribe('drugstore.findDoctorError', (e, data) => {
					uni.showToast({
						title: data.error.message,
						duration: 2000,
						icon: 'error',
					});
					this.$emit('findDoctorError', data);
				});
				GuideDiagnosis.INIT();
			},
			async getGroupInfo() {
				const res = await zimApi.api_commonApiQueryGroupInfo({
					groupId: this.gid,
				});
				const {
					result
				} = res.data;
				const groupMessage = result;
				this.groupMessage = groupMessage;
				const {
					groupUsers
				} = groupMessage;
				const users = {};
				groupUsers.map(v => {
					users[v.userId] = v;
					if (!v.avatar) {
						users[v.userId]['showAvatar'] = avatarNull;
					} else {
						users[v.userId]['showAvatar'] = v.avatar;
					}
				});
				this.groupMessage.users = users;
			},
			async getHistoryMsg() {
				const response = await zimApi.api_drugstoreQueryMessages({
					receiverUId: this.uid,
					groupId: this.gid,
					limit: 50,
				});
				const data = response.data.result.data;

				this.chatList = [...data];

				this.scrollBottom(1000);
			},
			renderInput() {
				return this.UserCanSpeak;
			},
			messageBelong(item) {
				const {
					owner,
					messageInfo
				} = item;
				const {
					type
				} = messageInfo;
				const {
					userId
				} = owner;

				if (type) {
					if (type === 'SysText' || type === 'FinishNoReply' || type === 'Finish' || type === 'Withdraw') {
						return 'system';
					}
				}

				if (userId == this.uid) {
					return 'user';
				} else {
					return 'to';
				}
			},
			messageTest(text) {
				if (!text) {
					uni.showToast({
						title: '请输入消息',
						duration: 2000,
						icon: 'error',
					});
					return false;
				}
				return true;
			},
			sendInputMessage(text) {
				if (this.messageTest(text)) {
					const messageInfo = {
						type: 'Text',
						body: {
							text,
							action: ''
						},
					};
					this.zimSendMessage(messageInfo);
				}
			},
			zimSendMessage(messageInfo) {
				const data = this.genMessageData(messageInfo);
				this.chatList.push(data);
				console.log(this.chatList);
				zim.sendMessage(data);
				this.clearInput();
				this.scrollBottom();
			},
			clearInput() {
				this.$refs.input && this.$refs.input.clearInput();
			},
			genMessageData(messageInfo) {
				const user = this.groupMessage.groupUsers.find(e => {
					return e.userId == this.uid;
				});
				const {
					avatar,
					userId,
					userName
				} = user;
				const userAvatar = avatar ? avatar : avatarNull;
				const name = userName ? userName : '缺少用户名称';
				const data = {
					createTime: Date.now(),
					clientMsgId: Date.now(),
					messageInfo,
					group: {
						groupId: this.gid,
					},
					owner: {
						userId: this.uid,
						userAvatar,
						userName: name,
					},
					sentStatus: 1,
					feature: ``,
					appType: 'pt', // 用来标记这个消息是用户自己发的
				};
				return data;
			},
			messageBelongDrugstore(item) {
				// 定制业务消息类型
				const {
					owner,
					messageInfo
				} = item;
				const {
					type
				} = messageInfo;
				if (type === 'Video') {
					return zimName.drugPlatform;
				}
			},
			renderTargetAvatar(targetUid) {
				return this.groupMessage.users[targetUid] && this.groupMessage.users[targetUid].showAvatar;
			},
			answerEvent(data) {
				GuideDiagnosis.answerQs(data);
				this.startAnswer = false;
			},
			handleResend(message) {
				message.sentStatus = 1;
				zim.sendMessage(message);
			},
			sendImageMessage(file) {
				const messageInfo = {
					type: 'Image',
					body: file,
				};
				this.zimSendMessage(messageInfo);
			},
			openImage(msg) {
				const {
					message: {
						messageInfo: {
							body: {
								fileUrl
							},
						},
					},
				} = msg;

				uni.previewImage({
					urls: [fileUrl],
				});
			},
			openRichLink(msg) {
				// console.log(msg)
				const {
					message
				} = msg;
				if (message.messageInfo.body.linkTitle == '用药申请') {
					// 点击用药申请
					console.log('click 用药申请');
				}
			},
			// GYJ新增代码
			navigateBack() {
				uni.navigateBack({
					delta: 1
				})
			},
			navigateToMiniProgram() {
				let userAccounts = uni.getStorageSync('DB_USER_ACCOUNTS')
				let tokenKey = uni.getStorageSync('DB_TOKEN_KEY')
				let claimNumber = uni.getStorageSync('DB_CLAIM_NUMBER')
				console.log(`pages/lipei/home/sucess?userAccounts=${userAccounts}&tokenkey=${tokenKey}&claimNumber=${claimNumber}`)
				uni.navigateToMiniProgram({
					appId: 'wxfdb0048182641ba6',
					path: `pages/lipei/home/sucess?userAccounts=${userAccounts}&tokenkey=${tokenKey}&claimNumber=${claimNumber}`,
					envVersion: 'trial',
					success(res) {
						// 打开成功
					}
				})
			}
			// -----------
		},
	};
</script>

<style lang="scss">
	view,
	text,
	image,
	input,
	textarea {
		box-sizing: border-box;
	}
</style>
<style lang="scss" scoped>
	.chatPageBox {
		height: 100%;
		overflow: hidden;
		box-sizing: border-box;
		padding-bottom: 22px;
		height: 100vh;
	}

	/* pages/im/index.wxss */
	page {
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
	}

	page {
		height: 100%;
		overflow: hidden;
		box-sizing: border-box;
		//padding-bottom: 22px;

		.chatPage {
			height: 100%;
			background: #f7f8fa;

			//height: 100vh;
			.chatContainer {
				height: 100%;
				display: flex;
				flex-direction: column;
				overflow: hidden;

				.chatContent {
					flex: 1;
					overflow: hidden;
					display: flex;

					.scroll {
						flex: 1;
						padding: 0 12px;

						.message {
							display: flex;
							margin-top: 20px;
							position: relative;
							justify-content: center;

							.msg_core {
								position: relative;
							}

							.sentStatus-1 {
								position: absolute;
								font-size: 12px;
								left: -50px;
								top: 10px;
							}

							.info_icon {
								background: #e0514c;
								line-height: 1.4;
								position: relative;
								font-family: arial, helvetica, sans-serif;
								color: white;
								font-weight: bold;
								font-size: 12px;
								max-width: 280px;

								&.sendStatus-3::after {
									display: block;
									position: absolute;
									left: -33px;
									top: 9px;
									content: '!';
									border-radius: 50%;
									border: 1px solid #e0514c;
									width: 0.53333rem;
									height: 0.53333rem;
									line-height: 0.58667rem;
									text-align: center;
									color: white;
									font-weight: normal;
									background: #e0514c;
									// content: '\F0E0';
									// color: #e0514c;
								}
							}

							&:nth-child(1) {
								margin-top: 0;
							}

							.avatar {
								display: block;
								width: 32px;
								height: 32px;
								border-radius: 50%;
							}

							.msg {
								max-width: 250px;

								// display: inline-flex;
								// position: relative;
								.name {
									font-size: 12px;
									display: block;
									color: #666;
									margin-bottom: 10px;
								}
							}
						}

						.user {
							display: flex;
							justify-content: flex-end;

							.avatar {
								margin-left: 10px;
							}

							.name {
								text-align: right;
							}
						}

						.to {
							justify-content: flex-start;

							.avatar {
								margin-right: 10px;
							}
						}
					}
				}
			}

			.chatInput {
				//height: 44px;
				background: #fff;
				display: flex;
				background: #f9f9f9;
				flex-direction: column;

				.chatInputBox {
					height: 55px;
				}
			}
		}
	}
</style>